home *** CD-ROM | disk | FTP | other *** search
- Path: news.clark.net!not-for-mail
- From: gusty@clark.net (Harlan Messinger)
- Newsgroups: comp.lang.c++
- Subject: Re: External access to private class variables
- Date: 2 Feb 1996 22:37:27 GMT
- Organization: Clark Internet Services, Inc., Ellicott City, MD USA
- Distribution: world
- Message-ID: <4eu3n7$rbi@clarknet.clark.net>
- References: <4ermr9$ii7@cloner2.ix.netcom.com> <ENNO.96Feb2203423@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- NNTP-Posting-Host: explorer.clark.net
- Mime-Version: 1.0
- Content-Type: TEXT/PLAIN; charset=ISO-8859-1
- Content-Transfer-Encoding: 8bit
- X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
-
- Enno Sandner (enno@inferenzsysteme.informatik.th-darmstadt.de) wrote:
- : In article <4ermr9$ii7@cloner2.ix.netcom.com> genescot@ix.netcom.com(Eugene S. Thompson ) writes:
- :
- : I was playing around with references and ran across this situation. I'm
- : sure it's not original, so I was hoping someone could tell me if it is
- : an intentional implementation of C++ or if it is a bug.
- :
- : class X
- : {
- : private:
- : int value;
- : public:
- : X (int n = 0) { value = n; }
- : int& GSValue () { return value; } // return a reference to the
- : // private member "value"
- : };
- : .
- : .
- : .
- : main ()
- : {
- : X x1 (20);
- :
- : printf ("%d\n", x1.GSValue ()); // 20
- :
- : int* pntr = &(x1.GSValue ());
- :
- : printf ("%d\n", *pntr); // 20
- :
- : *pntr = 30;
- : printf ("%d\n", x1.GSValue ()); // 30 -> We now have external
- : // access to a private member.
- : }
- :
- : I realize that this implementation is contrived, but I'm sure there are
- : additional ways of gaining such access. So, what's the deal?
- :
- : It's even possible to modify the private member directly:
- :
- : int main ()
- : {
- : X x1 (20);
- : printf ("%d\n", x1.GSValue ()); // 20
- : x1.GSValue()=30;
- : printf ("%d\n", x1.GSValue ()); // 30
- : }
- :
- : You return a non-const reference and therefore it's perfectly valid to
- : modify the referred variable. One should take care with services that
- : provide uncontrolled access to private members.
- :
- : Enno
-
- This isn't strange. An object can have several names and be pointed to by
- several pointers. Making one of those names private hides just that name.
- It doesn't hide any of the other names, and it doesn't hide the pointers
- to it.
-
- Treating your example for the sake of discussion as real code that
- someone wrote, all this means is that somebody didn't want the name "x"
- used to access that spot in memory, but wanted it to be called GSValue()
- instead. Perhaps GSValue() is a meaningful name for the intended user,
- and the current implementation of GSValue() is via an integer data
- member, but perhaps later on it will be via some other private mechanism.
- If that happens, the change will be invisible to the user, who will still
- use the public member reference function GSValue() just as before.
-